<template>
    <div class="login-container">
        <!-- 首页按钮 -->
        <el-button icon="ArrowLeft" circle class="home-button" @click="goToHome" />

        <el-card class="login-card" shadow="hover">
            <h2>欢迎回来</h2>

            <el-form :model="form" label-position="left" label-width="80px" @submit.prevent="login">
                <!-- 账号密码表单项 -->
                <div v-show="activeTab === 'account'">
                    <el-form-item label="账号">
                        <el-input v-model="form.username" placeholder="请输入账号" />
                    </el-form-item>
                    <el-form-item label="密码">
                        <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password />
                    </el-form-item>

                    <!-- 验证码 -->
                    <el-form-item label="验证码">
                        <el-row :gutter="10">
                            <el-col :span="14">
                                <el-input v-model="form.code" placeholder="请输入验证码" />
                            </el-col>
                            <el-col :span="10">
                                <img :src="codeUrl" alt="验证码" class="captcha-img" @click="getCode" />
                            </el-col>
                        </el-row>
                    </el-form-item>
                </div>

                <el-button native-type="submit" type="primary" class="submit-btn">登录</el-button>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import * as loginApi from '@/api/login'
import { user } from '@/stores/user.js'

const router = useRouter()
const userStore = user()

const activeTab = ref('account')
const form = ref({
    username: '',
    password: '',
    code: ''
})

const codeUrl = ref('')
const captchaKey = ref('') // 存储验证码 key

// 获取验证码
const getCode = async () => {
    try {
        const res = await loginApi.getCaptcha()
        codeUrl.value = res.data // base64 图片地址
        captchaKey.value = res.msg // 后端返回的验证码 key
    } catch (err) {
        console.error('获取验证码失败:', err)
    }
}

onMounted(() => {
    getCode()
})

const login = async () => {
    try {
        if (!form.value.username || !form.value.password || !form.value.code || !captchaKey.value) {
            alert('请填写完整信息')
            return
        }

        const params = {
            username: form.value.username,
            password: form.value.password,
            code: form.value.code,
            codeKey: captchaKey.value
        }

        const res = await loginApi.loginWithPassword(params)

        console.log('登录成功:', res.data)

        userStore.setToken(res.data.token)
        userStore.setUserInfo(res.data)
        localStorage.setItem('token', res.data.token)

        router.push('/main')
    } catch (err) {
        console.error('登录失败:', err)
        getCode() // 刷新验证码
    }
}

const goToRegister = () => {
    router.push('/register')
}

const goToHome = () => {
    router.push('/home')
}
</script>

<style lang="scss" scoped>
.captcha-img {
    width: 100%;
    cursor: pointer;
    border-radius: 4px;
    background-color: #f0f0f0;
}

.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    position: relative;

    .home-button {
        position: absolute;
        top: 20px;
        right: 20px;
        z-index: 10;
        background-color: white;
        border: 1px solid #ddd;
        color: #333;

        &:hover {
            background-color: #f0f0f0;
        }
    }

    .login-card {
        width: 100%;
        max-width: 420px;
        padding: 2rem;
        border-radius: 12px;
        background-color: #ffffffee;

        h2 {
            margin-bottom: 1.5rem;
            font-weight: 600;
            color: #333;
            text-align: center;
        }

        .submit-btn {
            width: 100%;
            margin-top: 1rem;
        }

        .register-tip {
            margin-top: 1rem;
            font-size: 0.9rem;
            color: #666;
            text-align: center;

            span {
                color: #4f8cf2;
                cursor: pointer;
                margin-left: 4px;

                &:hover {
                    text-decoration: underline;
                }
            }
        }
    }
}
</style>